<template>
  <div class="main">
    <div class="content">
      <el-row :gutter="20" style="margin-left: 60px">
        <el-col :span="18">
          <div>
            <el-form
              ref="form"
              :model="form"
              label-width="110px"
              :rules="rules"
              disabled
            >
              <el-form-item label="算法名称：" prop="algoName">
                <el-input
                  v-model="form.algoName"
                  size="small"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item label="算法语言：" prop="language">
                <el-input
                  v-model="form.language"
                  size="small"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item label="算法用途：" prop="purpose">
                <el-input
                  type="textarea"
                  v-model="form.purpose"
                  :autosize="{ minRows: 3, maxRows: 8 }"
                ></el-input>
              </el-form-item>
              <el-form-item label="备注：" prop="remarks">
                <el-input
                  type="textarea"
                  v-model="form.remarks"
                  :autosize="{ minRows: 3, maxRows: 8 }"
                ></el-input>
              </el-form-item>
              <!-- <el-form-item label="上传数据：" prop="file">
                <mine-upload
                  ref="upload"
                  :fileType="accept"
                  @change="onChange"
                ></mine-upload>
              </el-form-item>
              <el-form-item label="高校测试模型：" prop="modelCode">
                <el-select v-model="form.modelCode" placeholder="请选择">
                  <el-option
                    v-for="item in modelSelection"
                    :key="item.optCode"
                    :label="item.optName"
                    :value="item.optCode"
                  ></el-option>
                </el-select>
              </el-form-item> -->
              <el-form-item class="form-btn-row">
                <!-- <mine-button type="primary" @click="onCancel" secondary
                  >取 消
                </mine-button>
                <mine-button type="primary" @click="onSubmit"
                  >保 存
                </mine-button> -->
                <mine-button type="primary" @click="onCancel"
                  >返 回
                </mine-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
        <el-col :span="12"></el-col>
      </el-row>
    </div>
  </div>
</template>


<script>
import request from "@/modules/index/utils/request";
import qs from "qs";

export default {
  name: "addDict",
  props: {
    rowData: {
      type: Object,
    },
  },
  data() {
    return {
      path: "",
      form: {
        creater: "",
        algoName: "",
        language: "",
        counts: "",
        createTime: "",
        purpose: "",
        remarks: "",
        id: 0,
        number: 0,
        file: null,
        modelCode: "",
      },
      rules: {
        algoName: [
          { required: false, message: "请填写算法名称", trigger: "blur" },
        ],
        language: [
          { required: false, message: "请填写算法语言", trigger: "blur" },
        ],
      },
      modelSelection: [], // 高校测试模型下拉选项
    };
  },
  watch: {
    rowData: {
      handler(val) {
        // 如果是编辑页面，先做页面数据的回显
        if (val) {
          this.form = JSON.parse(JSON.stringify(val));
        }
      },
      immediate: true,
    },
  },
  computed: {
    accept() {
      return ".txt,.xls,.xlsx";
    },
  },
  methods: {
    async getModelSelection() {
      let params = {
        dirCode: "test_model_type",
      };
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: "/dictionary/TreeList",
              RequestMethod: "get",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: qs.stringify(params, { indices: false }),
              isStringParam: true,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              _self.modelSelection = result?.data[0].childrenParams;
            } else {
              _self.$message.error("获取函数数据失败");
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          "/dictionary/TreeList",
          "get",
          "application/json;charset=UTF-8",
          qs.stringify(params, { indices: false }),
          true,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200 && e.data.webInfo.requestId === uuid) {
              this.modelSelection = res?.data[0].childrenParams;
            } else {
              this.$message.error("获取函数数据失败");
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch("getDicBydirCode", params);
        if (res.data.status === 200) {
          this.modelSelection = res.data?.data[0].childrenParams;
        } else {
          this.$message.error("获取函数数据失败");
        }
      }
    },
    onChange(data) {
      this.form.file = data.file;
    },
    onSubmit() {
      let _this = this;
      this.$refs.form.validate(async (valid, object) => {
        let { form } = _this;
        form.type = 2;
        let formData = new FormData();
        formData.append("file", this.form?.file?.raw);
        if (valid) {
          if (this.$webview2.isWPF) {
            const uuid = this.$webview2.generateRandomUUID();
            await this.$webview2.sendWebView2(
              `/algoTemplateFile/update`,
              "post",
              "application/json;charset=UTF-8",
              form,
              false,
              uuid
            );
            await window.chrome.webview.addEventListener(
              "message",
              (e) => {
                let res = e.data.response;
                // TODO： 定制后台数据处理
                if (res.status === 200 && e.data.webInfo.requestId === uuid) {
                  this.$message.success(res.msg);
                  this.$emit("close");
                } else {
                  this.$message.error(res.msg || "编辑失败");
                  return;
                }
              },
              { once: true }
            );
          } else {
            request({
              url: `/algoTemplateFile/update`, //接口
              method: "post",
              data: form,
            }).then((response) => {
              let result = response.data;
              if (!result.success) {
                this.$message.error(result.msg || "编辑失败");
                return;
              }
              this.$message.success(result.msg || "编辑成功");
            });
          }
        }
      });
    },
    onCancel() {
      // this.form = {
      //   creater: "",
      //   algoName: "",
      //   language: "",
      //   id: 0,
      //   purpose: "0",
      //   // number: 0,
      // };
      this.$emit("close");
      // if (!this.$route.query.isCut) {
      //     !this.$route.query.isPredict ? this.$router.push("/code/list") : this.$router.push("/code/predictList");
      // } else {
      //     !this.$route.query.isPredict ? this.$router.push("/code/shortcut") : this.$router.push("/code/previewCodeCut");
      // }
    },
  },
  created() {
    // 获取高校测试模型下拉选项
    // this.getModelSelection();
  },
};
</script>

<style scoped lang="less">
/deep/.mine-upload .el-upload-dragger {
  width: 373px;
}
</style>
